package com.javatest.springboot3minio.controller;

import com.javatest.springboot3minio.controller.convertor.AttachmentDtoConvertor;
import com.javatest.springboot3minio.dao.AttachmentManageDao;
import com.javatest.springboot3minio.entity.AttachmentInfo;
import com.javatest.springboot3minio.utils.MinioBucketUtil;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MainController {
  private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
  private AttachmentManageDao attachmentManageDao;
  private AttachmentDtoConvertor attachmentDtoConvertor;

  @Autowired
  public void setAttachmentManageDao(AttachmentManageDao attachmentManageDao) {
    this.attachmentManageDao = attachmentManageDao;
  }

  @Autowired
  public void setAttachmentDtoConvertor(AttachmentDtoConvertor attachmentDtoConvertor) {
    this.attachmentDtoConvertor = attachmentDtoConvertor;
  }

  @GetMapping("/")
  public ModelAndView main() {
    final List<String> bucketNameList = MinioBucketUtil.listBucketNames();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("main");
    modelAndView.addObject("bucketNameList", bucketNameList);
    return modelAndView;
  }

  @GetMapping("/uploadFileView")
  public ModelAndView uploadFileView() {
    final List<String> bucketNameList = MinioBucketUtil.listBucketNames();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("uploadFile");
    modelAndView.addObject("bucketNameList", bucketNameList);
    return modelAndView;
  }

  @GetMapping("/downloadFileView")
  public ModelAndView downloadFileView() {
    final List<AttachmentInfo> attachmentList = attachmentManageDao.getAttachmentList(null, null);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("downloadFile");
    modelAndView.addObject(
        "attachmentList",
        attachmentList.stream()
            .map(attachmentDtoConvertor::getDtoFromDo)
            .collect(Collectors.toList()));
    return modelAndView;
  }
}
